//
//  OrderVc.m
//  
//
//  Created by chris on 15/12/26.
//
//

#import "OrderVc.h"
#import "OderCell.h"
#import "WuliaoViewController.h"
#import "OrderSearchView.h"
#import "cardChooseView.h"
#import "DataModel.h"
#import "UserModel.h"
#import "Macro.h"
#import "NSDate+Utils.h"
#import "UIViewController+order.h"
#import "HaokaViewController.h"
#import "KongkaViewController.h"
#import "QudaobiangengViewController.h"
#import "ReasonViewController.h"
#import "SelectDeliveryMethyVc.h"
#import "DitchManageChangeVc.h"

@interface OrderVc ()<UITableViewDataSource,UITableViewDelegate,cardChooseViewDelegate,UITextFieldDelegate>
{
    NSMutableArray *_tableDataArr;
    NSDictionary *allDict;
    OrderSearchView *headerView;
    UITableView *mytableView;

    cardChooseView *cardChooseView1;
    SelectTypeBean *selectCardBean;
}
@end

@implementation OrderVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"工单处理";
    if (_isFromList) {
        self.title = @"工单列表";
    }
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:nil action:nil];

    headerView = [[[NSBundle mainBundle] loadNibNamed:@"OrderSearchView" owner:self options:nil] firstObject];
    headerView.search1TF.placeholder = @"";
    headerView.search1TF.delegate = self;
    headerView.search1TF.keyboardType = UIKeyboardTypeNumberPad;
    headerView.search2TF.placeholder = @"--请选择--";
    headerView.search2TF.delegate = self;
    cardChooseView1 = [[[NSBundle mainBundle] loadNibNamed:@"cardChooseView" owner:nil options:nil] lastObject];
    cardChooseView1.delegate = self;
    NSMutableArray *cardList = [NSMutableArray array];
    [cardList addObjectsFromArray:@[[SelectTypeBean beanWithName:@"新建"],
//            [SelectTypeBean beanWithName:@"审核通过"],
//            [SelectTypeBean beanWithName:@"审核驳回"],
            [SelectTypeBean beanWithName:@"确认"],
            [SelectTypeBean beanWithName:@"发货"],
            [SelectTypeBean beanWithName:@"收货"]
    ]];
    cardChooseView1.cardList = cardList;
    headerView.search2TF.inputView = cardChooseView1;
    [headerView.searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    super.page = 1;

    mytableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    mytableView.delegate = self;
    mytableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mytableView.sectionHeaderHeight = 15.0;
    mytableView.sectionFooterHeight = 15.0;
    mytableView.dataSource = self;
    mytableView.tableHeaderView = headerView;
    mytableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        super.page = 1;
        [self requestList:NO];
    }];
    mytableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        super.page ++;
        [self requestList:NO];
    }];
    [self addSubview:mytableView];
    _tableDataArr =  [NSMutableArray array];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestList:YES];
}


#pragma mark 搜索事件
- (void)searchAction:(UIButton *)searchButton {
    DLog(@"搜索事件--");
    super.page = 1;
    [self requestList:YES];
}

#pragma mark-UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (_tableDataArr == nil ? 0 : _tableDataArr.count);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellId = @"oder";
    OderCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell)
    {
        cell = [[OderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    OrderDealModel *model = _tableDataArr[indexPath.row];
    NSString *idKey = model.userId;

    NSDictionary *dictionary = [allDict objectForKey:idKey];
    OrderDealDetailModel *orderDealDetailModel = [[OrderDealDetailModel alloc] initWithDictionary:dictionary error:nil];

    cell.orderNumLa.text = [NSString ignoreEmptyStr:model.id];
    //工单类型 1：空卡  2：号卡  3：物料  4：办公耗材  5：渠道信息变更  6：渠道经理变更
    cell.typeLa.text = [super getOrderTypeNameFromtypeId:model.type.intValue];
    //sign工单处理状态 0：新建  1：审核通过（type=5||type=6） 1：确认（type!=5||type!=6）  2:发货  3：收货  4：审核驳回
    cell.statusLa.text = [super getOrderStatusNameFromtypeId:model.type.intValue andSignId:model.sign.intValue];
    cell.dateLa.text = [[NSDate dateWithString:model.creatTime formatString:@"yyyyMMddHHmmss"] formatStringWithFormat:@"yyyy-MM-dd"];//20151202111348  2015-12-12
    cell.storeLa.text = [NSString ignoreEmptyStr:orderDealDetailModel.storeName];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderDealModel *model = _tableDataArr[indexPath.row];
    if (_isFromList) {//工单列表
        //先按照type过滤些简单的
        switch (model.type.intValue) {
            case 6:{//渠道经理变更
                DitchManageChangeVc *ditchManageChangeVc = [[DitchManageChangeVc alloc] init];
                ditchManageChangeVc.model = model;
                ditchManageChangeVc.type = ORDER_LOOK_TYPE;
                [self.navigationController pushViewController:ditchManageChangeVc animated:YES];
                return;
            }
            case 5:{//渠道信息变更 分4种1.门店名称变更  2.门店地址变更  3.银行账号变更  4.vpn账号变更
                QudaobiangengViewController *qudaobiangengViewController = [[QudaobiangengViewController alloc] init];
                qudaobiangengViewController.model = model;
                qudaobiangengViewController.type = ORDER_LOOK_TYPE;
                [self.navigationController pushViewController:qudaobiangengViewController animated:YES];
                return;
            }
            case 1:{//1空卡
                KongkaViewController * vc = [[KongkaViewController alloc]init];
                vc.model = model;
                vc.type = ORDER_LOOK_TYPE;
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
            case 2:{ //2：号卡
                HaokaViewController * vc = [[HaokaViewController alloc]init];
                vc.model = model;
                vc.type = ORDER_LOOK_TYPE;
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
            case 3 :{//3：物料
                WuliaoViewController * vc = [[WuliaoViewController alloc]init];
                vc.model = model;
                vc.type = ORDER_LOOK_TYPE;
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
                break;
            case 4 :{//4：办公耗材 (页面同上)
                WuliaoViewController * vc = [[WuliaoViewController alloc]init];
                vc.model = model;
                vc.type = ORDER_LOOK_TYPE;
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
                break;
        }
        DLog(@"工单列表工单列表S");
    } else {
        // 号卡、物料配送类的审核流程分四步：新建—》确认—》发货—》收货
// 配送类步骤1-新建          ((号卡)新建 ;          (空卡)新建;   办公耗材新建;  物料新建(5-4-8))   ;渠道变更新建  渠道经理变更
// 配送类步骤2-确认[发货确认] (号卡确认5-4-5        ;空卡/办公耗材确认(5-4-7);  物料确认(5-4-8))
// 配送类步骤3-发货          (号卡发货5-4-9)       ;空卡/办公耗材发货(5-4-11)  物料发货(5-4-12)
// 配速类步骤4-发货(最后一步-公共的) 选择配速方式,填写备注
        //先按照type过滤些简单的
        switch (model.type.intValue) {
            case 6:{//渠道经理变更
                DitchManageChangeVc *ditchManageChangeVc = [[DitchManageChangeVc alloc] init];
                ditchManageChangeVc.model = model;
                ditchManageChangeVc.type = ORDER_EDIT_TYPE;
                [self.navigationController pushViewController:ditchManageChangeVc animated:YES];
                return;
            }
            case 5:{//渠道信息变更 分4种1.门店名称变更  2.门店地址变更  3.银行账号变更  4.vpn账号变更
                QudaobiangengViewController *qudaobiangengViewController = [[QudaobiangengViewController alloc] init];
                qudaobiangengViewController.model = model;
                qudaobiangengViewController.type = ORDER_EDIT_TYPE;
                [self.navigationController pushViewController:qudaobiangengViewController animated:YES];
                return;
            }
            case 1:{//1空卡
                KongkaViewController * vc = [[KongkaViewController alloc]init];
                vc.model = model;
                vc.type = ORDER_EDIT_TYPE;
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
            case 2:{ //2：号卡
                HaokaViewController * vc = [[HaokaViewController alloc]init];
                vc.model = model;
                vc.type = ORDER_EDIT_TYPE;
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
            case 3 :{//3：物料
                WuliaoViewController * vc = [[WuliaoViewController alloc]init];
                vc.model = model;
                vc.type = ORDER_EDIT_TYPE;
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
                break;
            case 4 :{//4：办公耗材 (页面同上)
                WuliaoViewController * vc = [[WuliaoViewController alloc]init];
                vc.model = model;
                vc.type = ORDER_EDIT_TYPE;
                [self.navigationController pushViewController:vc animated:YES];
                return;
            }
                break;
        }

    }
}
#pragma mark-UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120*ratio_heigth+20;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 选择银行卡的代理
- (void)cancel {
    [self.view endEditing:YES];
}

- (void)chooseCard:(SelectTypeBean *)cardInfo {
    selectCardBean = cardInfo;
    [self.view endEditing:YES];
    NSLog(@"选择银行卡的代理.");
    headerView.search2TF.text = cardInfo.name;
}

- (void)cardChooseView:(UIPickerView *)cardChooseView didSelectRow:(NSInteger)row withCardBean:(SelectTypeBean *)cardInfo {
    selectCardBean = cardInfo;
    headerView.search2TF.text = cardInfo.name;
}

#pragma mark 请求数据
- (void)requestList:(BOOL)showDialog {
    NSString *sign = [self getOrderIdByOrderStatusName:headerView.search2TF.text withFlag:YES];
    NSString *type = [self getOrderIdByOrderStatusName:headerView.search2TF.text withFlag:NO];
    if (sign.intValue == 5) { //由于数据库确认和审核是一个状态，故在页面为了区分使用状态5，此处转回实际状态1
        sign = @"1";
        type = @"sh";
    }
    if ([sign isEqualToString:@""]) {
        type = @"";
    }

    if (_isFromList) {//工单列表
        [UserServices orderListByToken:[[AppDelegate appDelegate] getUserInfo].token
                                    id:headerView.search1TF.text//工单号
                                  sign:sign//工单处理状态
                                  type:type//工单类型
                                  page:kIntToString(super.page)
                              pageSize:kIntToString(kListPageSize)
                            showDialog:showDialog
                       completionBlock:^(int result, id responseObject) {
                           DLog(@"order = %@",responseObject);
                           if (result == API_Request_Success) {

                               NSDictionary *dictionary1 = responseObject[0];
                               NSArray *result = [dictionary1 objectForKey:@"data"];
                               NSMutableArray *list = [NSMutableArray array];
                               [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                                   OrderDealModel *model = [[OrderDealModel alloc] initWithDictionary:obj error:nil];
                                   if (model)
                                       [list addObject:model];
                               }];

                               NSDictionary *dictionary2 = responseObject[1];
                               allDict = dictionary2;

                               NSMutableArray *array = list;
                               if (super.page == 1) {
                                   [_tableDataArr removeAllObjects];
                                   [_tableDataArr addObjectsFromArray:array];
                                   [mytableView.footer resetNoMoreData];//重置有更多数据
                                   if (array == nil || array.count == 0) {
                                       //提示无数据
                                       [SVProgressHUD showErrorWithStatus:@"查无数据"];
                                   } else {
                                   }
                               }
                               else
                                   [_tableDataArr addObjectsFromArray:array];
                               if (array.count == 0) {
                                   super.page--;
                               }
                               [mytableView.header endRefreshing];
                               [mytableView.footer endRefreshing];
                               [mytableView reloadData];
                               if (array.count < kListPageSize)
                                   [mytableView.footer noticeNoMoreData];//没有更多数据
                           } else {
                               [mytableView.header endRefreshing];
                               [mytableView.footer endRefreshing];
                           }
                       }];
    } else {//工单处理
        [UserServices orderAuditListByToken:[[AppDelegate appDelegate] getUserInfo].token
                                         id:headerView.search1TF.text//工单号
                                       sign:sign//工单处理状态
                                       type:type//工单类型
                                       page:kIntToString(super.page)
                                   pageSize:kIntToString(kListPageSize)
                                 showDialog:showDialog
                            completionBlock:^(int result, id responseObject) {
                                DLog(@"order = %@",responseObject);
                                if (result == API_Request_Success) {

                                    NSDictionary *dictionary1 = responseObject[0];
                                    NSArray *result = [dictionary1 objectForKey:@"data"];
                                    NSMutableArray *list = [NSMutableArray array];
                                    [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                                        OrderDealModel *model = [[OrderDealModel alloc] initWithDictionary:obj error:nil];
                                        if (model)
                                            [list addObject:model];
                                    }];

                                    NSDictionary *dictionary2 = responseObject[1];
                                    allDict = dictionary2;

                                    NSMutableArray *array = list;
                                    if (super.page == 1) {
                                        [_tableDataArr removeAllObjects];
                                        [_tableDataArr addObjectsFromArray:array];
                                        [mytableView.footer resetNoMoreData];//重置有更多数据
                                        if (array == nil || array.count == 0) {
                                            //提示无数据
                                            [SVProgressHUD showErrorWithStatus:@"查无数据"];
                                        } else {
                                        }
                                    }
                                    else
                                        [_tableDataArr addObjectsFromArray:array];
                                    if (array.count == 0) {
                                        super.page--;
                                    }
                                    [mytableView.header endRefreshing];
                                    [mytableView.footer endRefreshing];
                                    [mytableView reloadData];
                                    if (array.count < kListPageSize)
                                        [mytableView.footer noticeNoMoreData];//没有更多数据
                                } else {
                                    [mytableView.header endRefreshing];
                                    [mytableView.footer endRefreshing];
                                }
                            }];
    }
}


#pragma mark UITextFieldDelegate 限制TextField位数的代理方法 12为
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 工单号
    if (textField == headerView.search1TF) {
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (toBeString.length > 20 && range.length!=1){ //最大20个字符
            textField.text = [toBeString substringToIndex:20];
            return NO;
        }
        if ([string chenkInputNSCharacterSetWithType:2])//kNumbers
        {
            return YES;
        }
        else
            return NO;
    }

    if (textField == headerView.search2TF) {
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (toBeString.length > 0 && range.length!=1){ //最大0个字符
            textField.text = [toBeString substringToIndex:0];
            return NO;
        }
        if ([string chenkInputNSCharacterSetWithType:6])//kEmpty
        {
            return YES;
        }
        else
            return NO;
    }
    return YES;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
